package cn.jinjimi.app.webview.utils;

import android.net.Uri;
import android.webkit.WebResourceResponse;

import cn.jinjimi.app.AppContext;
import cn.jinjimi.app.modules.Resource.NetResourceManager;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * 将网络请求映射到本地资源
 *
 * @author Jinsen
 * @date 16/4/7
 */
public class InterceptResponse {

    public static WebResourceResponse responseWithLocalFile(Uri url) throws IOException {
        if (url.getScheme().equals("http") || url.getScheme().equals("https")) {
            return responseWithLocalFile(url.toString());
        }
        return null;
    }

    public static WebResourceResponse responseWithLocalFile(String url) throws IOException {

        if (NetResourceManager.getInstance().containResource(url)) {
            WebResourceResponse webResourceResponse = NetResourceManager.getInstance().createWebResourceResponse(url);
            if (webResourceResponse != null)
                return webResourceResponse;

        } else if (LocalResource.LOCAL_RESOURCE_TABLE.containsKey(url)) {
            String resName = LocalResource.LOCAL_RESOURCE_TABLE.get(url);

            //find the resource type
            String type = resName.substring(resName.lastIndexOf(".") + 1);
            String mineType = LocalResource.RES_TYPE_TALE.get(type);

            return new WebResourceResponse(mineType == null ? "text/" + type : mineType, "UTF-8",
                    AppContext.getInstance().getAssets().open(resName));

        } else if (url.endsWith("/favicon.ico")) {

            return new WebResourceResponse("image/png", null,
                    new BufferedInputStream(AppContext.getInstance().getAssets().open("favicon.ico")));
        }

        return null;

    }

    final static class LocalResource {
        static HashMap<String, String> LOCAL_RESOURCE_TABLE = new HashMap<String, String>();

        static HashMap<String, String> RES_TYPE_TALE = new HashMap<>();

        static {
            LOCAL_RESOURCE_TABLE.put("http://assets.xrkcdn.com/framework/js/jquery-2.1.4.js", "jquery-2.1.4.js");
            LOCAL_RESOURCE_TABLE.put("http://assets.xrkcdn.com/framework/css/reset-1.0.0.css", "reset-1.0.0.css");

            RES_TYPE_TALE.put("js", "text/javascript");
            RES_TYPE_TALE.put("css", "text/css");

        }
    }

}
